package com.qf.data.listener;

import com.qf.common.model.DeviceModelValue;
import com.qf.data.service.DeviceModelValueService;
import com.qf.data.service.HeartBeatService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 接收mq中发来的传感器上报数据, 保存到mongodb中
 * @author 千锋健哥
 */
@Component
@Slf4j
public class MessageReciveListener {

    @Autowired
    private DeviceModelValueService deviceModelValueService;

    @Autowired
    private HeartBeatService heartBeatService;

    @RabbitHandler
    @RabbitListener(queues = {"qf.queue.value.device"})
    public void messageHandler(Channel channel, DeviceModelValue deviceModelValue, Message message) {
        try {
            log.info("qf-center-data服务接收传感器上报数据为:" + deviceModelValue);

            //调用service, 将数据保存到mongodb中
            deviceModelValueService.saveDeviceModelValue(deviceModelValue);

            //将传感器上报的数据作为心跳数据保存到redis中, 可以作为设备是否在线状态
            heartBeatService.savePing(deviceModelValue.getProduct_key(), deviceModelValue.getDevice());

            //手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
